# Importing Data
KOREA <- read_excel("C:/Users/Biniam/Desktop/Documents/Academic/Thesis/Analysis Folder/Excel Files/Yemen/Korea.xlsx")

# Checking the Imported Data
View(KOREA)

# Creating Time Series Data
KOREA_ts <- ts(KOREA, start=c(2008,01), end=c(2019,07), frequency=12)

# Viewing and Checking the Created Time Series Data
KOREA_ts
sum(is.na(KOREA_ts))
library(forecast)
KOREA_ts <- tsclean(KOREA_ts)

# Step – 1 of the Box-Jenkins Methodology (Identification: Plotting the Time Series Data)
plot(KOREA_ts)
plot(aggregate(KOREA_ts,FUN=mean))

# Decomposing
KOREA_ts_decomp <- decompose(KOREA_ts)
plot(KOREA_ts_decomp)

# Testing for Stationarity
acf(KOREA_ts, lag.max=20)
pacf(KOREA_ts, lag.max=20)

# To see any seasonal effect
boxplot(KOREA_ts~cycle(KOREA_ts))

# To remove trend effect
KOREA_ts_diff <- diff(KOREA_ts)
plot(KOREA_ts_diff)

# To remove variance effect
KOREA_ts_log <- log(KOREA_ts)
plot(KOREA_ts_log)

# To remove both (Trend and Variance) effects
KOREA_ts_both <- diff(log(KOREA_ts))
plot(KOREA_ts_both)


# Dealing with ACF and PACF
install.packages("tseries")
library(tseries)
acf(KOREA_ts, lag.max=20)
acf(log(KOREA_ts), lag.max=20)
acf(diff(KOREA_ts), lag.max=20)
acf(diff(log(KOREA_ts)), lag.max=20)
pacf(KOREA_ts, lag.max=20)
pacf(log(KOREA_ts), lag.max=20)
pacf(diff(KOREA_ts), lag.max=20)
pacf(diff(log(KOREA_ts)), lag.max=20)

# Step-2 of the Box-Jenkins Methodology (Estimating the appropriate model)
KOREA_ts_model <- auto.arima(KOREA_ts)
KOREA_ts_model
KOREA_ts_model <- auto.arima(KOREA_ts, ic="aic", trace = TRUE)
KOREA_ts_model

# Step-3 of the Box-Jenkins Methodology (Diagnosis Checking)
library(tseries)
plot.ts(KOREA_ts_model$resid)
acf(KOREA_ts_model$residuals, main='ACF Residual')
pacf(KOREA_ts_model$residuals, main='ACF Residual')
Box.test(KOREA_ts_model$resid, lag=20, type="Ljung-Box")

# Forecasting
options(max.print=1000000)
library(forecast)
KOREA_ts_forecast <- forecast (KOREA_ts_model, level=c(95), h=257)
plot(KOREA_ts_forecast)
KOREA_ts_forecast             


write.table(KOREA_ts_forecast, file="Korea_TSA.csv", sep=",")
